package com.aptech.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.map.ObjectMapper;

import com.aptech.exception.BaseException;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

public class OccurException extends MethodFilterInterceptor{

	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		ObjectMapper jsonMapper = new ObjectMapper();
		Map<String, Object> response = new HashMap<String, Object>();
		Map<String, Object> status = new HashMap<String, Object>();
		
		HttpServletResponse httpResponse = ServletActionContext.getResponse();
		httpResponse.setCharacterEncoding("UTF-8");
		
		try{
			String result = invocation.invoke();
			status.put("status", "200");
			status.put("message", "成功");
			response.put("status", status);

			HttpServletRequest request = ServletActionContext.getRequest();
			Object data = request.getAttribute("response_data");

			if (data != null) {
				response.put("data", data);
			}
			
			httpResponse.getWriter().print(jsonMapper.writeValueAsString(response));
		}catch(Exception e){
			//log
			
			if(e instanceof BaseException){
				status.put("errCode", ((BaseException) e).getCode());
				status.put("message", e.getMessage());
				response.put("status", status);
				
				httpResponse.getWriter().print(jsonMapper.writeValueAsString(response));
			}
			
			if(e instanceof RuntimeException){
				
			}
		}finally{
			httpResponse.getWriter().flush();
			httpResponse.getWriter().close();
			
			return null;
		}
	}
}
